package com.luomo.java.juc.collection;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 集合类不安全问题
 * <p>
 * 故障现象
 * java.util.ConcurrentModificationException
 * <p>
 * 导致原因
 * 并发争抢修改导致
 * <p>
 * ArrayList
 * 解决方案
 * 1.new Vector<>();
 * 2.Collections.synchronizedList(new ArrayList<>());
 * 3.JUC new CopyOnWriteArrayList<>();
 * <p>
 * HashSet
 * 1.Collections.synchronizedSet(new HashSet<>());
 * 2.new CopyOnWriteArraySet<>();
 * <p>
 * HashMap
 * 1.new ConcurrentHashMap<>();
 * 2.Collections.synchronizedMap(new HashMap<>());
 * <p>
 * 优化建议
 *
 * @author LiuMei
 * @date 2021-04-09.
 */
public class ContainerNotSafeDemo {

    public static void main(String[] args) {
//        List<String> list = new ArrayList<>();
//        List<String> list = new Vector<>();
//        List<String> list = Collections.synchronizedList(new ArrayList<>());
//        Set<String> list = new HashSet<>();
//        Set<String> list = Collections.synchronizedSet(new HashSet<>());
//        Set<String> list = new CopyOnWriteArraySet<>();
//        Map<String,String> list = new HashMap<>();
        Map<String, String> list = new ConcurrentHashMap<>();
//        Map<String, String> list = Collections.synchronizedMap(new HashMap<>());
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                list.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0, 8));
                System.out.println(list);
            }).start();
        }
    }

}
